package org.csu.sei.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.csu.sei.common.BaseConstant;
import org.csu.sei.common.ReturnJson;
import org.csu.sei.entity.Category;
import org.csu.sei.service.ICategoryService;
import org.csu.sei.service.ITitleService;
import org.csu.sei.util.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.csu.sei.common.BaseConstant.ErrorCode.*;
import static org.csu.sei.common.BaseConstant.Status.INVISIBLE;
import static org.csu.sei.common.BaseConstant.Status.VISIBLE;


@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private ICategoryService categoryService;

    @Resource
    private ITitleService titleService;


    @GetMapping("/{catId}")
    @ApiOperation(value = "根据id查询类型")
    public JSONObject queryCategory(@PathVariable Long catId){
        JSONObject data = new JSONObject();
        Category category=categoryService.queryCategory(catId);
        if(category==null){
            return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
        };
        data.put("category", category);
        return ReturnJson.successRes(data);
    }

    //新建类型
    @PostMapping("")
    @ApiOperation(value = "新建并插入类型")
    public JSONObject insertCategory(@RequestBody Category category){
        JSONObject data = new JSONObject();
        System.out.println(category);
        Category result=categoryService.insertCategory(category);
        if(result.getId()==-1){
            return ReturnJson.defaultFailureRes(CATEGORY_PARENT_NOT_EXIST);
        }
        else if(result.getId()==-2){
            return ReturnJson.defaultFailureRes(CATEGORY_IS_LEFT);
        }
        else if(result.getId()==-3){
            return ReturnJson.defaultFailureRes(CATEGORY_TITLE_NOT_EXIST);
        }
        data.put("category",result);
        return ReturnJson.successRes(data);
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新类型")
    public JSONObject updateCategory(@PathVariable Long id,@RequestBody Category category){
        category.setId(id);
        int result=categoryService.updateCategory(category);
        if(result==-1){
            return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
        }
        else if(result==-2){
            return ReturnJson.defaultFailureRes(CATEGORY_PARENT_NOT_EXIST);
        }
        else if(result==-3){
            return ReturnJson.defaultFailureRes(CATEGORY_TITLE_NOT_EXIST);
        }
        else if(result == -4){
            return ReturnJson.defaultFailureRes(CATEGORY_CIRCLEY);
        }
        else if(result == -5){
            return ReturnJson.defaultFailureRes(CATEGORY_IS_LEFT);
        }
        return ReturnJson.ackWithMsg("ok");
    }

    //删除类型
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除类型")
    public JSONObject deleteCategory(@PathVariable Long id){
        int result=categoryService.deleteCategory(id);
        if(result==0){
            return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
        }
        return ReturnJson.ackWithMsg("ok");
    }

    //获取指定id的子类型
    @GetMapping("/{id}/children")
    @ApiOperation(value = "查询指定id类型的一级子类型子节点")
    public JSONObject queryChildrenCategory(
            @PathVariable Long id,
            @RequestHeader(value = "token",required = false)String token
    ){
        List<Category> list;
        if(token==null){
            Category category=categoryService.queryCategory(id);
            if(category==null || category.getCategoryStatus()==INVISIBLE.getCode()){
                return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
            }
            list=categoryService.queryChildren(id,false);
        }
        else{
            Category category=categoryService.queryCategory(id);
            if(category==null){
                return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
            }
            list=categoryService.queryChildren(id,true);
        }
        JSONObject json=new JSONObject();
        json.put("category_list",list);
        return ReturnJson.successRes(json);
    }

    //更改类型名称
    @PatchMapping("/{id}/name")
    @ApiOperation(value = "更改类型名称")
    public JSONObject changeCategoryName(@PathVariable Long id,@RequestBody Map<String,String> map){
        String name=map.get("name");
        int result=categoryService.changeCategoryName(id,name);
        if(result==-1){
            return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
        }
        else if(result==-2){
            return ReturnJson.defaultFailureRes(CATEGORY_PARENT_NOT_EXIST);
        }
        return ReturnJson.ackWithMsg("ok");
    }

    //更改顺序
    @PatchMapping("/order")
    @ApiOperation(value = "更改类型顺序")
    public JSONObject changeCategorySortOrder(@RequestBody Map<String,Object>map ){
        Long id= new Long((int)map.get("id"));
        Long pid= new Long((int)map.get("pid"));
        List<Long> childrenOrder = (List)(map.get("childrenOrder"));
        int result = categoryService.changeOrder(id,pid,childrenOrder);
        if (result==-1){
            return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
        }
        else if (result==-2){
            return ReturnJson.defaultFailureRes(CATEGORY_PARENT_NOT_EXIST);
        }
        else if (result==-3){
            return ReturnJson.defaultFailureRes(CATEGORY_IS_LEFT);
        }
        return ReturnJson.ackWithMsg("ok");
    }

    //展示全部类型别
    @GetMapping("/all")
    @ApiOperation(value = "展示全部类型")
    public JSONObject queryAllCategory( @RequestHeader(value = "token",required = false)String token){
        JSONObject json=new JSONObject();
        if(token==null){
            json.put("category_list",categoryService.queryAllCategory(false));
        }
        else if(TokenUtil.getUserData(token).getRole() <= 1){
            json.put("category_list",categoryService.queryAllCategory(true));
        }
        return ReturnJson.successRes(json);
    }

    // 当前节点下所有子节点
    @GetMapping("/{id}/all")
    @ApiOperation(value = "获取指定id类型的所有子类型子节点")
    public JSONObject queryAllChildrenCategory(
            @PathVariable Long id,
            @RequestHeader(value = "token",required = false)String token
            ){
        JSONObject json=new JSONObject();
        if(token==null){
            json.put("category_list",categoryService.queryALLChildrenCategory(id,false));
        }
        else{
            json.put("category_list",categoryService.queryALLChildrenCategory(id,true));
        }
        return ReturnJson.successRes(json);
    }

    //导航栏接口
    @GetMapping("/bar")
    @ApiOperation(value = "获取导航栏类型")
    public JSONObject queryNavBar(){
        JSONObject json=new JSONObject();
        json.put("title_list",categoryService.queryBar());
        return ReturnJson.successRes(json);
    }

    @GetMapping("/router")
    public JSONObject router(@RequestHeader(value = "token",required = false)String token){
        JSONObject list;
        if(token==null){
            list=categoryService.router(false);
        }
        else{
            list=categoryService.router(true);
        }
        return ReturnJson.successRes(list);
    }

    //只有后台能请求
    @GetMapping("/tree")
    public JSONObject tree(
            @RequestHeader(value = "token",required = false)String token,
            @RequestParam(value = "include",required = false)String include
            ){
        ReturnJson returnJson;
        if(include==null){
            returnJson = new ReturnJson(categoryService.tree(false));
        }
        else if(include.equals("home")){
            returnJson = new ReturnJson(categoryService.tree(true));
        }
        else{
            returnJson = null;
        }
        return JSON.parseObject(JSON.toJSONString(returnJson));
    }

    @GetMapping("/{id}/recentUpdateTime")
    public JSONObject recentUpdateTime(@PathVariable Long id){
        LocalDateTime time =categoryService.getLatestUpdateTime(id);
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String timeStr=dateFormat.format(time);
        JSONObject json = new JSONObject();
        json.put("recentUpdateTime",timeStr);
        return ReturnJson.successRes(json);
    }

    @DeleteMapping("/deleteSome")
    public  JSONObject deletSome(@RequestBody List<Long> idList){
        JSONObject data = new JSONObject();
        boolean allOk = true;
        int count = 0;
        try {
            count = categoryService.deleteSome(idList);
        }catch (Exception e){
            allOk = false;
        }
        data.put("count",count);
        data.put("stat",allOk);
        return  ReturnJson.successRes(data);
    }

    @PatchMapping("/setVisible")
    public JSONObject setVis(@RequestBody List<Long> idList){
        int count = categoryService.setLook(idList,VISIBLE.getCode());
        return ReturnJson.ackWithMsg("ok");
    }

    @PatchMapping("/setInvisible")
    public JSONObject setInvis(@RequestBody List<Long> idList){
        int count = categoryService.setLook(idList,INVISIBLE.getCode());
        return ReturnJson.ackWithMsg("ok");
    }

    @PutMapping("/titleCategoryList")
    @ApiOperation(value = "更改title下的类型")
    public JSONObject changeTitleCategory(@RequestBody List<JSONObject> list ){
        List<Long> used = new ArrayList<>();
        int index=1;
        for(JSONObject json : list){
            Long titleId=Long.parseLong((json.get("titleId")).toString());
            String titleName = (String)json.get("titleName");
            titleService.changeName(titleId,titleName);
            List array = (List) json.get("categoryList");
            //for (Object object:array) {
            for (int i=0 ; i<array.size() ; ++i)
            {
                Object object = array.get(i);
                Map<String, Object> category = (Map<String, Object>) object;
                Long id = Long.parseLong((category.get("id")).toString());
                used.add(id);
                categoryService.changeTitleCategory(id, titleId);
                categoryService.changeOrder(id,index);
                index+=1;
            }
        }
        categoryService.changeUnusedCategoryOrder(index);
        return ReturnJson.ackWithMsg("ok");
    }

    @GetMapping("/titleCategoryList")
    public JSONObject getTitleList(){
        JSONObject json = categoryService.titleCategoryList();
        return ReturnJson.successRes(json);
    }

}

